class Parcelle < ActiveRecord::Base

  belongs_to :typeculture
  
  has_many :labtoparcelles
  has_many :labours, :through => :labtoparcelles

  has_many :putoparcelles
  has_many :pulves, :through => :putoparcelles

  has_many :factoparcelles
  has_many :factures, :through => :factoparcelles

  has_many :zonetopas, :single_save => true
  has_many :zones, :through => :zonetopas

  #retourne la somme des surface d'un jeu de parcelles
  def sum_surfaces(parcelles)
    s=0
    parcelles.each do |parcelle| 
      s = s + parcelle.surface
    end
    s
  end
  
  def percent_of_zone(zone_id)
    zone = Zone.find(zone_id)
    zonetopa = Zonetopa.find_by(zone_id, self.id)
    percent = zonetopa.value * 100 / self.surface
    return percent
  end

#debut Labtofacture  
  def new_zonetopa_attributes=(zonetopa_attributes)
    zonetopa_attributes.each do |attributes|
      zonetopas.build(attributes)
    end
  end
 
  def existing_zonetopa_attributes=(zonetopa_attributes)
    zonetopas.reject(&:new_record?).each do |zonetopa|
      attributes = zonetopa_attributes[zonetopa.id.to_s]
      if attributes
        zonetopa.attributes = attributes
      else
#        zonetopa.delete(zonetopa)
        sql = "DELETE FROM zonetopas WHERE id = #{zonetopa.id} LIMIT 1"
        ActiveRecord::Base.connection.execute(sql)
      end
    end
  end
 
  def save_zonetopas
    zonetopas.each do |zonetopa|
      zonetopa.save(false)
    end
  end

end
